package com.gulimall.gulimallsearch.service.impl;

import com.alibaba.fastjson.JSON;
import com.common.to.SkuEsModel;
import com.gulimall.gulimallsearch.config.GulimallelasticConfig;
import com.gulimall.gulimallsearch.constant.ESConstant;
import com.gulimall.gulimallsearch.feign.productFeign;
import com.gulimall.gulimallsearch.service.mallSearchService;
import com.gulimall.gulimallsearch.vo.SearchResult;
import com.gulimall.gulimallsearch.vo.SearchVo;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author mayifan
 * @version 1.0
 * @date 2024-12-25 10:13
 */
@Service
public class mallSearchServiceImpl implements mallSearchService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Autowired
    productFeign productFeign;

    @Override
    public SearchResult search(SearchVo vo) {

        SearchResult searchResult = null;
        SearchRequest searchRequest = buildSearchRequest(vo);
        try {
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, GulimallelasticConfig.COMMON_OPTIONS);
            searchResult = buildSearchResult(searchResponse, vo);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return searchResult;
    }

    //        "query": {
//            "bool": {
//                "must": [ {"match": {  "skuTitle": "华为" }} ],
//                "filter": [
//                { "term": { "catelogId": "225" } },
//                {
//                    "range": {}
//                 }
//    模糊匹配、过滤（按照属性、分类、品牌、价格区间、库存），排序，分页，高亮，聚合分析
    private SearchRequest buildSearchRequest(SearchVo vo) {

        /**
         * 1、过滤（按照属性、分类、品牌、价格区间、库存）
         */
        // 1、构建bool-query
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        // 1.1、must-模糊匹配、
        if (!StringUtils.isEmpty(vo.getKeyword())) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle", vo.getKeyword()));
        }

        // 1.2.1、filter-按照三级分类id查询
        if (vo.getCatalog3Id() != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("catelogId", vo.getCatalog3Id()));
        }
        // 1.2.2、filter-按照品牌id查询
        if (vo.getBrandId() != null && vo.getBrandId().size() != 0) {
            boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId", vo.getBrandId()));
        }


        // 1.2.3、filter-按照是否有库存进行查询
        if (vo.getHasStock() != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("hasStock", vo.getHasStock() == 1));
        }

        // 1.2.4、filter-按照区间进行查询  1_500/_500/500_
        if (!StringUtils.isEmpty(vo.getSkuPrice())) {
            RangeQueryBuilder skuPrice = QueryBuilders.rangeQuery("skuPrice");
            String[] s = vo.getSkuPrice().split("_");
            if (vo.getSkuPrice().startsWith("_")) {
                skuPrice.gte(0);
                skuPrice.lte(s[0]);
            } else if (vo.getSkuPrice().endsWith("_")) {
                skuPrice.gte(s[0]);
            } else if (s.length == 2) {
                skuPrice.gte(Integer.parseInt(s[0])).lte(Integer.parseInt(s[1]));
            }
            boolQueryBuilder.filter(skuPrice);
        }


        // 1.2.5、filter-按照属性进行查询
        List<String> attrs = vo.getAttrs();
        if (attrs != null && attrs.size() != 0) {

            attrs.forEach(attr -> {
                BoolQueryBuilder queryBuilders = new BoolQueryBuilder();

                String[] split = attr.split("_");
                queryBuilders.must(QueryBuilders.termQuery("attrs.attrId", split[0]));
                String[] split1 = split[1].split(":");
                queryBuilders.must(QueryBuilders.termsQuery("attrs.attrValue", split1));

                NestedQueryBuilder nestedQueryBuilder = new NestedQueryBuilder("attrs", queryBuilders, ScoreMode.None);
                boolQueryBuilder.filter(nestedQueryBuilder);
            });

        }
        searchSourceBuilder.query(boolQueryBuilder);

        /**
         * 2、排序，分页，高亮，
         */
        // 2.1、排序  eg:sort=saleCount_desc/asc
        if (!StringUtils.isEmpty(vo.getSort())) {
            String sort = vo.getSort();
            String[] s = sort.split("_");
            searchSourceBuilder.sort(s[0], s[1].equals("asc") ? SortOrder.ASC : SortOrder.DESC);

        }

        // 2.2、分页
        searchSourceBuilder.from((vo.getPageNum() - 1) * ESConstant.PRODUCT_PAGESIZE);
        searchSourceBuilder.size(ESConstant.PRODUCT_PAGESIZE);

        // 2.3、高亮highlight
        if (!StringUtils.isEmpty(vo.getKeyword())) {
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            searchSourceBuilder.highlighter(highlightBuilder);
        }

        /**
         * 3、聚合分析
         */
        // 3、聚合
        // 3.1、按照品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg").field("brandId").size(ESConstant.PRODUCT_PAGESIZE);
        TermsAggregationBuilder brandName_agg = AggregationBuilders.terms("brandName_agg").field("brandName").size(ESConstant.PRODUCT_PAGESIZE);
        TermsAggregationBuilder brandImg_agg = AggregationBuilders.terms("brandImg_agg").field("brandImg").size(ESConstant.PRODUCT_PAGESIZE);
        brand_agg.subAggregation(brandName_agg);
        brand_agg.subAggregation(brandImg_agg);

        searchSourceBuilder.aggregation(brand_agg);


        // 3.2、按照catelog聚合
        TermsAggregationBuilder catelog_agg = AggregationBuilders.terms("catelog_agg").field("catelogId").size(ESConstant.PRODUCT_PAGESIZE);
        TermsAggregationBuilder catelogName_agg = AggregationBuilders.terms("catelogName_agg").field("catelogName").size(ESConstant.PRODUCT_PAGESIZE);
        catelog_agg.subAggregation(catelogName_agg);

        searchSourceBuilder.aggregation(catelog_agg);


        // 3.3、按照attrs聚合
        NestedAggregationBuilder attrs_nested = AggregationBuilders.nested("attrs", "attrs");
        TermsAggregationBuilder attrIdAgg = AggregationBuilders.terms("attrIdAgg").field("attrs.attrId").size(10);
        TermsAggregationBuilder attrNameAgg = AggregationBuilders.terms("attrNameAgg").field("attrs.attrName").size(50);
        TermsAggregationBuilder attrValueAgg = AggregationBuilders.terms("attrValueAgg").field("attrs.attrValue");
        attrIdAgg.subAggregation(attrNameAgg);
        attrIdAgg.subAggregation(attrValueAgg);
        attrs_nested.subAggregation(attrIdAgg);

        searchSourceBuilder.aggregation(attrs_nested);

        System.out.println(searchSourceBuilder.toString());


        SearchRequest searchRequest = new SearchRequest(new String[]{ESConstant.PRODUCT_INDEX}, searchSourceBuilder);
        return searchRequest;
    }

    private SearchResult buildSearchResult(SearchResponse searchResponse, SearchVo vo) {


        SearchResult result = new SearchResult();
        SearchHits hits = searchResponse.getHits();
        // 1、返回的所有查询到的商品
        List<SkuEsModel> product = new ArrayList<>();
        if (hits != null && hits.getHits().length != 0) {
            hits.forEach(hit -> {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                if (!StringUtils.isEmpty(vo.getKeyword())) {
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String s = skuTitle.getFragments()[0].toString();
                    skuEsModel.setSkuTitle(s);
                }
                product.add(skuEsModel);
            });
        }


        result.setProducts(product);


        // 2、当前所有商品涉及到的所有属性
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        ParsedNested attrs = searchResponse.getAggregations().get("attrs");
        ParsedLongTerms attrIdAgg = attrs.getAggregations().get("attrIdAgg");
        for (Terms.Bucket bucket : attrIdAgg.getBuckets()) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
//            设置属性id
            attrVo.setAttrId(bucket.getKeyAsNumber().longValue());
//            设置属性名
            ParsedStringTerms attrNameAgg = bucket.getAggregations().get("attrNameAgg");
            Terms.Bucket buckets = attrNameAgg.getBuckets().get(0);
            attrVo.setAttrName(buckets.getKeyAsString());
//            设置属性值
            ParsedStringTerms attrValueAgg = bucket.getAggregations().get("attrValueAgg");
            List<String> list = attrValueAgg.getBuckets().stream().map(bucket1 -> {

                String keyAsString = bucket1.getKeyAsString();
                return keyAsString;
            }).collect(Collectors.toList());
            attrVo.setAttrValue(list);
            attrVos.add(attrVo);
        }
        result.setAttrs(attrVos);

        // 3、当前涉及到的所有品牌
        ParsedLongTerms brand_agg = searchResponse.getAggregations().get("brand_agg");
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        for (Terms.Bucket bucket : brand_agg.getBuckets()) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            brandVo.setBrandId(bucket.getKeyAsNumber().longValue());

            ParsedStringTerms brandName_agg = bucket.getAggregations().get("brandName_agg");
            brandVo.setBrandName(brandName_agg.getBuckets().get(0).getKeyAsString());
            brandVo.setBrandImg(((ParsedStringTerms) (bucket.getAggregations().get("brandImg_agg"))).getBuckets().get(0).getKeyAsString());

            brandVos.add(brandVo);
        }
        result.setBrands(brandVos);

        // 4、当前商品所涉及的分类信息
        ParsedLongTerms catalog_agg = searchResponse.getAggregations().get("catelog_agg");

        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        List<? extends Terms.Bucket> buckets = catalog_agg.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            // 得到分类id
            String keyAsString = bucket.getKeyAsString();
            catalogVo.setCatalogId(Long.parseLong(keyAsString));

            // 得到分类名
            ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catelogName_agg");
            String catalog_name = catalog_name_agg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(catalog_name);
            catalogVos.add(catalogVo);
        }
        result.setCatalogs(catalogVos);

        //===========以上从聚合信息获取到=============
        // 5、分页信息-页码
        result.setPageNum(vo.getPageNum());

        // 6、分页信息-总记录数
        long value = hits.getTotalHits().value;
        result.setTotal(value);

        // 7、分页信息-总页码-计算
        int pages = (int) ((int) value % ESConstant.PRODUCT_PAGESIZE == 0 ? value / ESConstant.PRODUCT_PAGESIZE : value / ESConstant.PRODUCT_PAGESIZE + 1);
        result.setTotalPages(pages);

        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 1; i <= pages; i++) {
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);

//        面包屑导航数据
        if (vo.getAttrs() != null && vo.getAttrs().size() > 0) {
            List<SearchResult.NavVo> navs = vo.getAttrs().stream().map(attr -> {
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                String[] s = attr.split("_");
                navVo.setNavValue(s[1]);
                String name = productFeign.infoName(Long.parseLong(s[0]));
                navVo.setName(name);

                // 8.1.3、设置面包屑跳转链接(当点击该链接时剔除点击属性)
                // 取消了这个面包屑以后，我们就要跳转到那个地方，将请求地址的url里面的当前置空
                // 拿到所有的查询条件，去掉当前
                String replace = replaceQueryString(vo, attr, "attrs");
                navVo.setLink("http://search.gulimall.com/list.html" + (replace.isEmpty() ? "" : "?" + replace));
                return navVo;
            }).collect(Collectors.toList());
            result.setNavs(navs);
        }

        System.out.println(searchResponse.toString());
        System.out.println(result.toString());
        return result;
    }

    private String replaceQueryString(SearchVo param, String value, String key) {
        String queryString = param.get_queryString();
        String encode = null;
        try {
            encode = URLEncoder.encode(value, "UTF-8");
            encode = encode.replace("+", "20%");//浏览器对空格编码和java不一样
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return queryString.replace("&" + key + "=" + encode, "");
    }
}
